<template>
  <div class="electron-demo">
    <h2>Electron 窗口管理演示</h2>

    <div class="button-group">
      <button @click="createNewWindow">创建新窗口</button>
      <button @click="createModalWindow">创建模态窗口</button>
      <button @click="sendMessageToWindow" :disabled="!currentWindowId">
        发送消息
      </button>
      <button @click="broadcastMessage">广播消息</button>
      <button @click="closeWindow" :disabled="!currentWindowId">
        关闭窗口
      </button>
    </div>

    <div class="input-group" v-if="currentWindowId">
      <input v-model="messageText" placeholder="输入要发送的消息" />
    </div>

    <div v-if="windowInfo" class="window-info">
      <h3>窗口信息：</h3>
      <pre>{{ JSON.stringify(windowInfo, null, 2) }}</pre>
    </div>

    <div class="message-list" v-if="messages.length">
      <h3>收到的消息：</h3>
      <div v-for="(msg, index) in messages" :key="index" class="message-item">
        <span class="message-time">{{ msg.time }}</span>
        <span class="message-content">{{ msg.content }}</span>
      </div>
    </div>

    <div v-if="error" class="error-message">
      {{ error }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from "vue";

const currentWindowId = ref<string>("");
const windowInfo = ref<any>(null);
const error = ref<string>("");
const messageText = ref<string>("");
const messages = ref<Array<{ time: string; content: string }>>([]);

// 检查是否有初始数据
onMounted(async () => {
  const initialData = await window.electronAPI.window.getInitialData();
  console.log("初始数据:", initialData);

  if (initialData) {
    messages.value.push({
      time: new Date().toLocaleTimeString(),
      content: `收到初始数据: ${JSON.stringify(initialData)}`,
    });
  }

  // 监听其他窗口发来的消息
  window.electronAPI.ipcRenderer.on("window-message", (event, data) => {
    messages.value.push({
      time: new Date().toLocaleTimeString(),
      content: `收到消息: ${JSON.stringify(data)}`,
    });
  });

  // 组件卸载时清理监听器
  onUnmounted(() => {
    window.electronAPI.ipcRenderer.off("window-ready");
    window.electronAPI.ipcRenderer.off("window-message");
  });
});

// 创建新窗口
async function createNewWindow() {
  try {
    const result = await window.electronAPI.window.create({
      url: "/index.html",
      windowId: `window-${Date.now()}`,
      width: 800,
      height: 600,
      data: {
        message: "这是从父窗口传递的初始数据",
        timestamp: Date.now(),
      },
    });
    console.log("创建窗口结果:", result);

    if (result.success) {
      currentWindowId.value = result.windowId || "";
      error.value = "";
    } else {
      error.value = result.error || "创建窗口失败";
    }
  } catch (e) {
    error.value = e instanceof Error ? e.message : "创建窗口时发生错误";
  }
}

// 创建模态窗口
async function createModalWindow() {
  try {
    const result = await window.electronAPI.window.create({
      url: "/index.html",
      windowId: `modal-${Date.now()}`,
      width: 400,
      height: 300,
      modal: true,
      data: {
        message: "这是模态窗口的初始数据",
        timestamp: Date.now(),
      },
    });

    if (result.success) {
      currentWindowId.value = result.windowId || "";
      error.value = "";
    } else {
      error.value = result.error || "创建模态窗口失败";
    }
  } catch (e) {
    error.value = e instanceof Error ? e.message : "创建模态窗口时发生错误";
  }
}

// 发送消息到指定窗口
async function sendMessageToWindow() {
  if (!currentWindowId.value || !messageText.value) return;

  try {
    const result = await window.electronAPI.window.sendMessage(
      currentWindowId.value,
      "window-message",
      {
        message: messageText.value,
        from: "parent-window",
        timestamp: Date.now(),
      }
    );

    if (result.success) {
      messageText.value = "";
      error.value = "";
    } else {
      error.value = result.error || "发送消息失败";
    }
  } catch (e) {
    error.value = e instanceof Error ? e.message : "发送消息时发生错误";
  }
}

// 广播消息给所有窗口
async function broadcastMessage() {
  if (!messageText.value) return;

  try {
    const result = await window.electronAPI.window.broadcastMessage(
      "window-message",
      {
        message: messageText.value,
        from: "broadcast",
        timestamp: Date.now(),
      }
    );

    if (result.success) {
      messageText.value = "";
      error.value = "";
    } else {
      error.value = result.error || "广播消息失败";
    }
  } catch (e) {
    error.value = e instanceof Error ? e.message : "广播消息时发生错误";
  }
}

// 关闭窗口
async function closeWindow() {
  if (!currentWindowId.value) return;

  try {
    const result = await window.electronAPI.window.close(currentWindowId.value);
    if (result.success) {
      currentWindowId.value = "";
      windowInfo.value = null;
      error.value = "";
    } else {
      error.value = result.error || "关闭窗口失败";
    }
  } catch (e) {
    error.value = e instanceof Error ? e.message : "关闭窗口时发生错误";
  }
}

// 获取窗口信息
async function getWindowInfo() {
  if (!currentWindowId.value) return;

  try {
    const result = await window.electronAPI.window.getInfo(
      currentWindowId.value
    );
    if (result.success) {
      windowInfo.value = result.data;
      error.value = "";
    } else {
      error.value = result.error || "获取窗口信息失败";
    }
  } catch (e) {
    error.value = e instanceof Error ? e.message : "获取窗口信息时发生错误";
  }
}
</script>

<style scoped>
.electron-demo {
  padding: 20px;
}

.button-group {
  margin: 20px 0;
  display: flex;
  gap: 10px;
}

.input-group {
  margin: 20px 0;
}

.input-group input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: #4caf50;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.window-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.window-info pre {
  margin: 0;
  white-space: pre-wrap;
}

.message-list {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.message-item {
  padding: 8px;
  border-bottom: 1px solid #eee;
}

.message-time {
  color: #666;
  margin-right: 10px;
  font-size: 0.9em;
}

.message-content {
  color: #333;
}

.error-message {
  margin-top: 20px;
  padding: 10px;
  background-color: #ffebee;
  color: #c62828;
  border-radius: 4px;
}
</style>
